import { Vec3 } from '@/core/types';
import { BlockType } from '@/blocks/types';
import { EntityData } from '@/entities/types';

export interface WorldData {
  version: string;
  timestamp: number;
  playerData: PlayerData;
  chunks: ChunkData[];
  entities: EntityData[];
  gameTime: number;
  worldSettings: WorldSettings;
}

export interface PlayerData {
  position: Vec3;
  rotation: { x: number; y: number };
  health: number;
  hunger: number;
  inventory: InventoryData;
  gameMode: string;
}

export interface InventoryData {
  items: ItemStack[];
  selectedSlot: number;
}

export interface ItemStack {
  type: BlockType;
  count: number;
  slot: number;
}

export interface ChunkData {
  x: number;
  z: number;
  blocks: BlockType[][][];
  lastModified: number;
}

export interface WorldSettings {
  seed: number;
  gameMode: string;
  difficulty: string;
  allowCheats: boolean;
}

export interface SaveInfo {
  id: string;
  name: string;
  timestamp: number;
  version: string;
  gameMode: string;
  lastPlayed: number;
}

export class SaveSystem {
  private static readonly SAVE_VERSION = '1.0.0';
  private static readonly SAVE_PREFIX = 'webcraft_save_';

  public async saveWorld(saveId: string, worldData: WorldData): Promise<boolean> {
    try {
      // 设置版本和时间戳
      worldData.version = SaveSystem.SAVE_VERSION;
      worldData.timestamp = Date.now();

      // 序列化世界数据
      const serializedData = JSON.stringify(worldData);
      
      // 压缩数据（简化版 - 在实际应用中可以使用更好的压缩算法）
      const compressedData = this.compressData(serializedData);
      
      // 保存到本地存储
      const saveKey = SaveSystem.SAVE_PREFIX + saveId;
      localStorage.setItem(saveKey, compressedData);
      
      // 更新保存信息
      this.updateSaveInfo(saveId, worldData);
      
      console.log(`World saved successfully: ${saveId}`);
      return true;
    } catch (error) {
      console.error('Failed to save world:', error);
      return false;
    }
  }

  public async loadWorld(saveId: string): Promise<WorldData | null> {
    try {
      const saveKey = SaveSystem.SAVE_PREFIX + saveId;
      const compressedData = localStorage.getItem(saveKey);
      
      if (!compressedData) {
        console.warn(`Save not found: ${saveId}`);
        return null;
      }
      
      // 解压数据
      const serializedData = this.decompressData(compressedData);
      
      // 反序列化世界数据
      const worldData: WorldData = JSON.parse(serializedData);
      
      // 验证数据完整性
      if (!this.validateWorldData(worldData)) {
        console.error('Invalid world data');
        return null;
      }
      
      console.log(`World loaded successfully: ${saveId}`);
      return worldData;
    } catch (error) {
      console.error('Failed to load world:', error);
      return null;
    }
  }

  public listSaves(): SaveInfo[] {
    const saves: SaveInfo[] = [];
    
    try {
      // 获取保存信息
      const saveInfoData = localStorage.getItem('webcraft_save_info');
      if (saveInfoData) {
        const saveInfoMap: Record<string, SaveInfo> = JSON.parse(saveInfoData);
        saves.push(...Object.values(saveInfoMap));
      }
      
      // 按最后游戏时间排序
      saves.sort((a, b) => b.lastPlayed - a.lastPlayed);
    } catch (error) {
      console.error('Failed to list saves:', error);
    }
    
    return saves;
  }

  public deleteSave(saveId: string): boolean {
    try {
      // 删除世界数据
      const saveKey = SaveSystem.SAVE_PREFIX + saveId;
      localStorage.removeItem(saveKey);
      
      // 更新保存信息
      const saveInfoData = localStorage.getItem('webcraft_save_info');
      if (saveInfoData) {
        const saveInfoMap: Record<string, SaveInfo> = JSON.parse(saveInfoData);
        delete saveInfoMap[saveId];
        localStorage.setItem('webcraft_save_info', JSON.stringify(saveInfoMap));
      }
      
      console.log(`Save deleted: ${saveId}`);
      return true;
    } catch (error) {
      console.error('Failed to delete save:', error);
      return false;
    }
  }

  private updateSaveInfo(saveId: string, worldData: WorldData): void {
    try {
      // 获取现有保存信息
      let saveInfoMap: Record<string, SaveInfo> = {};
      const saveInfoData = localStorage.getItem('webcraft_save_info');
      if (saveInfoData) {
        saveInfoMap = JSON.parse(saveInfoData);
      }
      
      // 更新或创建保存信息
      saveInfoMap[saveId] = {
        id: saveId,
        name: saveId, // 简化版，使用ID作为名称
        timestamp: worldData.timestamp,
        version: worldData.version,
        gameMode: worldData.worldSettings.gameMode,
        lastPlayed: Date.now()
      };
      
      // 保存更新后的信息
      localStorage.setItem('webcraft_save_info', JSON.stringify(saveInfoMap));
    } catch (error) {
      console.error('Failed to update save info:', error);
    }
  }

  private compressData(data: string): string {
    // 简化的压缩 - 在实际应用中可以使用LZ4、gzip等
    // 这里只是基础的字符串压缩
    return btoa(data);
  }

  private decompressData(compressedData: string): string {
    // 简化的解压
    return atob(compressedData);
  }

  private validateWorldData(worldData: any): boolean {
    // 基础的数据验证
    if (!worldData || typeof worldData !== 'object') {
      return false;
    }
    
    // 检查必需的字段
    const requiredFields = ['version', 'playerData', 'chunks', 'entities', 'worldSettings'];
    for (const field of requiredFields) {
      if (!(field in worldData)) {
        console.error(`Missing required field: ${field}`);
        return false;
      }
    }
    
    // 检查版本兼容性
    if (worldData.version !== SaveSystem.SAVE_VERSION) {
      console.warn(`Version mismatch: expected ${SaveSystem.SAVE_VERSION}, got ${worldData.version}`);
      // 在实际应用中，这里可以实现版本迁移逻辑
    }
    
    return true;
  }

  public clearAllGameData(): boolean {
    try {
      // 获取所有需要清除的键
      const keysToRemove: string[] = [];
      
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key && (
          key.startsWith(SaveSystem.SAVE_PREFIX) ||
          key === 'webcraft_save_info' ||
          key.startsWith('webcraft_') // 包括聊天记录等其他游戏数据
        )) {
          keysToRemove.push(key);
        }
      }
      
      // 删除所有游戏相关数据
      keysToRemove.forEach(key => {
        localStorage.removeItem(key);
      });
      
      console.log(`Cleared ${keysToRemove.length} game data entries`);
      return true;
    } catch (error) {
      console.error('Failed to clear all game data:', error);
      return false;
    }
  }

  public getStorageUsage(): { used: number; available: number } {
    try {
      // 计算已使用的存储空间
      let used = 0;
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);
        if (key && key.startsWith(SaveSystem.SAVE_PREFIX)) {
          const value = localStorage.getItem(key);
          if (value) {
            used += key.length + value.length;
          }
        }
      }
      
      // 估算可用空间（LocalStorage通常有5-10MB限制）
      const estimated = 5 * 1024 * 1024; // 5MB
      const available = Math.max(0, estimated - used);
      
      return { used, available };
    } catch (error) {
      console.error('Failed to calculate storage usage:', error);
      return { used: 0, available: 0 };
    }
  }
}